package com.zhugang.week13.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @program algorithms
 * @description: levelOrder
 * @author: chanzhugang
 * @create: 2022/12/28 18:37
 */
public class LevelOrder4 {

    /**
     * 剑指offer 32-III 从上到下打印二叉树 (之字打印)
     * https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/
     *
     * @param root
     * @return
     */
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        /**
         * 先处理每层，最后奇数层反转
         */
        dfs(root, 0);
        for (int i = 1; i < result.size(); i += 2) {
            // 反转
            Collections.reverse(result.get(i));
        }
        return result;
    }

    private void dfs(TreeNode root, int level) {
        if (root == null) {
            return;
        }
        if (level > result.size() - 1) {
            result.add(new ArrayList<>());
        }
        result.get(level).add(root.val);
        dfs(root.left, level + 1);
        dfs(root.right, level + 1);

    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}